package ca.etsmtl.log430.lab3;

import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * System B.1
 */

public class REGProgressFilter extends Thread {

	// Declarations

	boolean done;

	PipedReader inputPipe = new PipedReader();
	PipedWriter outputPipe = new PipedWriter();

	public REGProgressFilter(PipedWriter inputPipe,
			PipedWriter outputPipe) {

		try {

			// Connect inputPipe
			this.inputPipe.connect(inputPipe);
			System.out.println("REGProgressFilter :: connected to upstream filter.");

			// Connect outputPipe
			this.outputPipe = outputPipe;
			System.out.println("REGProgressFilter :: connected to downstream filter.");

		} catch (Exception Error) {
			System.out.println("REGProgressFilter :: error connecting to other filters.");

		} // try/catch

	} // Constructor

	// This is the method that is called when the thread is started
	public void run() {

		// Declarations

		char[] characterValue = new char[1];
		// char array is required to turn char into a string
		String lineOfText = "";
		// string is required to look for the keyword
		int integerCharacter; // the integer value read from the pipe

		try {

			done = false;

			while (!done) {

				integerCharacter = inputPipe.read();
				characterValue[0] = (char) integerCharacter;

				if (integerCharacter == -1) { // pipe is closed

					done = true;

				} else {

					if (integerCharacter == '\n') { // end of line

						System.out.println("REGProgressFilter :: received: " + lineOfText + ".");

						String[] parts = lineOfText.split(" ");
						if((parts[1].equals("RIS") || parts[1].equals("DIF")) && Integer.parseInt(parts[2]) < 50){
							
							System.out.println("REGProgressFilter :: sending: "
									+ lineOfText + " to output pipe.");
							lineOfText += new String(characterValue);
							outputPipe
							.write(lineOfText, 0, lineOfText.length());
							outputPipe.flush();
							
							
						}

						lineOfText = "";

					} else {

						lineOfText += new String(characterValue);

					} // if //

				} // if

			} // while

		} catch (Exception error) {

			System.out.println("REGProgressFilter:: Interrupted.");

		} // try/catch

		try {

			inputPipe.close();
			System.out.println("REGProgressFilter " + ""
					+ ":: input pipe closed.");

			outputPipe.close();
			System.out.println("REGProgressFilter " + ""
					+ ":: output pipe closed.");

		} catch (Exception error) {

			System.out.println("REGProgressFilter " + ""
					+ ":: Error closing pipes.");

		} // try/catch

	} // run

} // class